package com.woniuxy.joylifeshop.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.woniuxy.joylifeshop.configuration.AlipayConfig;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RequestMapping("/pay")
@RestController
public class PayController {

    @GetMapping("/order")
    public void pay(HttpServletRequest request, HttpServletResponse response){
        System.out.println(0);
        System.out.println(request.getParameter("WIDout_trade_no"));
        if(request.getParameter("WIDout_trade_no")!=null){
            try {
                // 商户订单号，商户网站订单系统中唯一订单号，必填
                String out_trade_no = request.getParameter("WIDout_trade_no");
                // 订单名称，必填
                String subject = request.getParameter("WIDsubject");
                System.out.println(subject);
                // 付款金额，必填
                String total_amount=request.getParameter("WIDtotal_amount");
                // 商品描述，可空
                String body = null;
                body = request.getParameter("WIDbody");

                // 超时时间 可空
                String timeout_express="2m";
                // 销售产品码 必填
                String product_code="QUICK_WAP_WAY";
                /**********************/
                // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
                //调用RSA签名方式
                AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
                AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();

                // 封装请求支付信息
                AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
                model.setOutTradeNo(out_trade_no);
                model.setSubject(subject);
                model.setTotalAmount(total_amount);
                model.setBody(body);
                model.setTimeoutExpress(timeout_express);
                model.setProductCode(product_code);
                model.setGoodsType("0");

                alipay_request.setBizModel(model);
                // 设置异步通知地址
                alipay_request.setNotifyUrl(AlipayConfig.notify_url);
                // 设置同步地址
                alipay_request.setReturnUrl(AlipayConfig.return_url);

                // form表单生产
                String form = "";
                // 调用SDK生成表单
                form = client.pageExecute(alipay_request).getBody();
                response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
                response.getWriter().write(form);//直接将完整的表单html输出到页面
                response.getWriter().flush();
                response.getWriter().close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/returnpay")
    public boolean returnPay(HttpServletRequest request){
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            params.put(name, valueStr);
        }
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号
        try {
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = false;
        try {
            verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA2");
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //请在这里根据验证结果加上商户的业务逻辑程序代码
        if(verify_result){
            System.out.println("验证成功");
            return true;
        }else{
            System.out.println("验证失败");
            return false;
        }
    }
}
